package ExperimentSix.Tensorflow;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class Worker {
    public static void main(String[] args) {
        // 启动三个Worker，分别连接到不同或相同的Master端口55952和端口55953
        startWorkerForMaster1();
        startWorkerForMaster1();
        startWorkerForMaster2();
    }

    private static void startWorkerForMaster1() {
        try (Socket socket = new Socket("localhost", 55952);
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
             BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {

            int taskCount = Integer.parseInt(in.readLine()); // 接收任务数量
            System.out.println("Worker接收到Master1的任务总数:: " + taskCount);
            // 执行任务和发送结果
            for (int i = 0; i < taskCount; i++) {
                int oneresult = i;
                out.println(oneresult); // 发送结果给Master
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void startWorkerForMaster2() {
        try (Socket socket = new Socket("localhost", 55953);
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
             BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {

            int taskCount = Integer.parseInt(in.readLine()); // 接收任务数量
            System.out.println("Worker接收到Master2的任务总数: " + taskCount);
            // 执行任务和发送结果的逻辑
            for (int i = 0; i < taskCount; i++) {
                int result = i;
                out.println(result); // 发送结果给Master
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}